import { Component, trigger, state, style, transition, animate } from '@angular/core';
import { NavController } from 'ionic-angular';
import { DetailPage } from '../detail/detail';

import { Business } from '../../model/business';
import { BusinessService } from '../../service/business.service';

declare const Blazy;
declare const MD5;
declare const wx;

@Component({
    selector: 'page-home',
    templateUrl: 'home.html',
    animations: [
        trigger('flyInOut', [
            state('in', style({ transform: 'translateX(0)' })),
            transition(':enter', [
                style({ transform: 'translateX(-100%)' }),
                animate(350)
            ]),
            transition(':leave', [
                animate(350, style({ transform: 'translateX(100%)' }))
            ])
        ])
    ],
    providers: [BusinessService]
})
export class HomePage {
    businesses: Business[];
    slideOptions: any;
    pageNum: number;

    constructor(
        private navCtrl: NavController,
        private businessService: BusinessService
    ) {
        this.slideOptions = {
            autoplay: 3500,
            pager: true,
            initialSlide: 1,
            loop: true
        };
        this.pageNum = 1;
    };

    ionViewWillEnter() {
        this.businessService.list(this.pageNum.toString(), '6', '').then(res => {
            this.businesses = res.list;
        });
    };
    
    // 图片懒加载
    ionViewDidEnter() {
        let blazy = new Blazy({
            src: 'data-blazy',
            success: function(ele){}
        });
    };
       
    // 查看商家详情
    viewDetail(id) {
        this.navCtrl.push(DetailPage, { id: id });
    };

    // 跳转至会员中心的float button
    goToVipCenter() {
        window.location.href = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxf14a7da52439d10b&redirect_uri=http%3A%2F%2Fqqxs.justbamboo.cn%2Fvip%2Findex.html&response_type=code&scope=snsapi_base&state=vip#wechat_redirect';
    };

    // 下拉加载
    getMoreBusiness(infiniteScroll) {
        this.pageNum++;
        this.businessService.list(this.pageNum.toString(), '6', '').then(res => {
            infiniteScroll.complete();
            let i = 0;
            let items = res.list;
            let length = items.length;
            if(length === 0){
                infiniteScroll.enable(false);
            }else{
                for (; i < length; i++) {
                    this.businesses.push(items[i]);
                };
            };
        });
    }
}
